package com.wfm.files;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * description: 主要验证channel的map映射时，position，size ，当有换行时，size的取值问题。
 * 12345
 * 6789
 *
 * 0-6，即12345\r  会换行
 * 0-7:即12345\r\n 会换行
 * 5,3：\r\n6      会换行
 * 6,3：\n67换行    会换行
 *
 * 但是如果连起来：12345\r  \n6789 只会换1行
 *
 * 12345\n
 * 6789\n
 * 所以我们以为：0，6，6,5 这样就可以读到两行内容，并且都有换行
 * 实际上：最后一行没有换行。
 */
public class FileChannelDemo {
    public static void main(String[] args) throws IOException {
        String fileAPath = "input.txt"; // 输入文件
        String fileBPath = "output.txt"; // 输出文件
        List<MultiThreadedFileProcessorOptimized.LineInfo> lines = new ArrayList<>();
        lines.add(new MultiThreadedFileProcessorOptimized.LineInfo(0, 6));
        lines.add(new MultiThreadedFileProcessorOptimized.LineInfo(6, 5));
        transferLines(fileAPath, fileBPath,lines );
    }
    private static void transferLines(String fileAPath, String fileBPath, List<MultiThreadedFileProcessorOptimized.LineInfo> lines) throws IOException {
        try (FileChannel sourceChannel = FileChannel.open(Paths.get(fileAPath), StandardOpenOption.READ);
             FileChannel destChannel = FileChannel.open(Paths.get(fileBPath), StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {

            for (MultiThreadedFileProcessorOptimized.LineInfo lineInfo : lines) {
                long position = lineInfo.position;
                int length = lineInfo.length;

                // 从 sourceChannel 读取指定区域
                MappedByteBuffer sourceBuffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, position, length);
                System.out.println("Reading line from position: " + position + ", length: " + length+"  ");

                // 将数据写入 destChannel
                destChannel.write(sourceBuffer);
            }
        }
    }
}
